﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using DevExpress.UserSkins;
using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using DevExpress.XtraBars.Helpers;
using CNotebook;
using G2Encryption;

namespace NotebookS2
{
    public partial class Login : RibbonForm
    {
        public Login()
        {
            InitializeComponent();
        }
        public bool IsAlreadyOpen { get; set; }
        public MainMenu MainForm { get; set; }
        public string Password { get; set; }
        public UserUnit ActiveUser { get; set; }
        public string Department { get; set; }
        public string ConnectionString { get; set; }


        public string GetLicenseKey()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";


            if (File.Exists(sPath) == true)
            {


                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("LicenseKey") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);


                            break;
                        }

                    }
                } while (input != null);


            }
            return _OUTPUT_STRING;

        }

        public string GetConnectionString()
        {
            string sPath = System.Windows.Forms.Application.StartupPath.ToString() + "\\config.conf";
            string _OUTPUT_STRING = "";


            if (File.Exists(sPath) == true)
            {


                StreamReader sr = File.OpenText(sPath);
                string input;

                do
                {
                    input = sr.ReadLine();
                    if (input != null)
                    {

                        if (input.StartsWith("ConnectionString") == true)
                        {
                            int iStart = input.IndexOf("=");
                            _OUTPUT_STRING = input.Substring(iStart + 1);

                            EncryptionManager oManager = new EncryptionManager();

                            oManager.PasswordHash = "P@@Sw0rd";
                            oManager.SaltKey = "S@LT&KEY";
                            oManager.VIKey = GetLicenseKey();

                            string _cstring = oManager.Decrypt(_OUTPUT_STRING);
                            _OUTPUT_STRING = _cstring;
                            break;
                        }

                    }
                } while (input != null);


            }
            return _OUTPUT_STRING;

        }

        SqlException BindCompany()
        {
            try
            {
                CompanyManager oManager = new CompanyManager();

                cboCompany.Properties.DisplayMember = "CompanyName";
                cboCompany.Properties.ValueMember = "ConnectionString";
                
                oManager.ConnectionString = GetConnectionString();
                SqlException ex = oManager.Open();

                if (ex != null)
                {
                    return ex;
                }
                cboCompany.Properties.DataSource = oManager.BrowseCompany();
                oManager.Close();

                cboCompany.Properties.Columns.Clear();
                DevExpress.XtraEditors.Controls.LookUpColumnInfo col;

                col = new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CompanyName", "CompanyName", 100);


                cboCompany.Properties.Columns.Add(col);
                cboCompany.Properties.ShowHeader = false;

                cboCompany.Refresh();

                return null;
            }
            catch (SqlException ex)
            {
                return ex;
            }

        }
        public bool Authenticate(string _CONNECTIONSTRING, string sUser, string sPassword)
        {
            UserManager oUserManager = new UserManager();

            //oUserManager.ConnectionString = "Data Source=localhost;Initial Catalog=NB-COMMON;User Id=sqladm;Password=nidaros;";
            oUserManager.ConnectionString = _CONNECTIONSTRING;
            oUserManager.Open();

            bool isAuthenticated = oUserManager.IsAuthenticated(sUser, sPassword);
            this.ActiveUser = oUserManager.ActiveUser;
            

            oUserManager.Close();

            this.IsAlreadyOpen = true;
            return isAuthenticated;
        }

        void Authenticate()
        {
            UserManager oManager = new UserManager();
            
            MainMenu oForm = this.MainForm;

            if(cboCompany.EditValue == null)
            {
                barStaticItem1.ItemAppearance.Normal.ForeColor = System.Drawing.Color.Red;
                barStaticItem1.Caption = "No selected company!!! Please choose company to log in!!!!";
                return;
                
            }

            if (Authenticate(cboCompany.EditValue.ToString(), txtUserID.Text, txtPassword.Text) == true)
            {

                oForm.ConnectionString = cboCompany.EditValue.ToString();
                oForm.Company = cboCompany.Text.ToString();
                oForm.WindowState = FormWindowState.Maximized;
                oForm.ActiveUserID = txtUserID.Text.ToUpper();
                oForm.AccessCode = ActiveUser.AccessCode;
                oForm.Department = ActiveUser.Department;
                oForm.UserName = ActiveUser.UserName;
                oForm.IsMultipleWarehouse = ActiveUser.IsMultiWarehouse;
                oForm.DefaultWarehouse = ActiveUser.DefaultWarehouse;
                oForm.Password = this.txtPassword.Text;
                oForm.Text = cboCompany.Text;
                oForm.LoginWindow = this;
                this.IsAlreadyOpen = true;
                this.Visible = false;
            }
            else
            {
                barStaticItem1.ItemAppearance.Normal.ForeColor = System.Drawing.Color.Red;
                barStaticItem1.Caption = "Please insert correct User name or Password.";
                txtUserID.Focus();
                txtUserID.SelectAll();
            }
            
        }

    
        private void Login_Load(object sender, EventArgs e)
        {

            this.FormBorderEffect = DevExpress.XtraEditors.FormBorderEffect.None;

            SqlException SqlEx = BindCompany();

            if (SqlEx != null)
            {
                MessageBox.Show(SqlEx.Message.ToString(), "Sql Connection", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
            MainForm.Close();
            Application.ExitThread();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            Authenticate();
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnOK_Click(sender, e);
            }
        }

        private void txtPassword_Enter(object sender, EventArgs e)
        {
            txtPassword.SelectAll();
        }

      
        private void txtUserID_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Authenticate();
            }
        }

        private void txtPassword_KeyDown_1(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Authenticate();
            }
        }

        private void cboCompany_Click(object sender, EventArgs e)
        {
            barStaticItem1.Caption = "";
        }

        private void txtUserID_Click(object sender, EventArgs e)
        {
            
        }

        private void txtPassword_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            barStaticItem1.Caption = "";
        }

        private void txtUserID_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            barStaticItem1.Caption = "";
        }

        private void cboCompany_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            barStaticItem1.Caption = "";
        }

        private void barStaticItem2_ItemClick(object sender, ItemClickEventArgs e)
        {
            this.timer1.Enabled = true;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Height == 210)
            {
                this.Height = 250;
                pictureEdit1.Height = 196;
                this.timer1.Enabled = false;
            }
            else
            {
                this.Height = 210;
                pictureEdit1.Height = 156;
                this.timer1.Enabled = false;
                
            }
        }

        private void pictureEdit1_Resize(object sender, EventArgs e)
        {
            
        }

        private void Login_Resize(object sender, EventArgs e)
        {
            if (this.Height >= 250)
            {
                labelControl1.Visible = true;
                labelControl2.Visible = true;
            }
            else
            {
                labelControl1.Visible = false;
                labelControl2.Visible = false;
            }
          
        }

      
        
    }
}
